package pe.com.bbva.mantenimiento.bo.impl;

import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import pe.com.bbva.mantenimiento.bo.KitMaterialBO;
import pe.com.bbva.mantenimiento.dao.KitMaterialDAO;
import pe.com.bbva.mantenimiento.domain.KitMaterial;
import pe.com.stefanini.core.bo.GenericBOImpl;
import pe.com.stefanini.core.bo.Grid;
import pe.com.stefanini.core.exceptions.BOException;
import pe.com.stefanini.core.exceptions.DAOException;

@Service("kitMaterialBO")
public class KitMaterialBOImpl extends GenericBOImpl<KitMaterial> implements KitMaterialBO{
	
	@Resource
	private KitMaterialDAO kitMaterialDAO;
	
	public boolean validate(KitMaterial kitMaterial) throws BOException, DAOException{
		KitMaterial materialBuscar = new KitMaterial();
		materialBuscar.setKit(kitMaterial.getKit());
		materialBuscar.setUbigeo(kitMaterial.getUbigeo());
		materialBuscar.setTipoMaterial(kitMaterial.getTipoMaterial());
		List<KitMaterial> materialesTmp = findKits(materialBuscar);
		if(materialesTmp!=null && !materialesTmp.isEmpty()){
			KitMaterial materialTmp = materialesTmp.get(0);
			Calendar cal = Calendar.getInstance();
			cal.setTime(kitMaterial.getFechaInicio());
			cal.add(Calendar.DAY_OF_MONTH, -1);
			materialTmp.setFechaFin(cal.getTime());
			this.doSave(materialTmp);
		}
		return true;
	}
	
	public KitMaterial findById(Long id) throws BOException {
		KitMaterial kitMaterial = super.findById(KitMaterial.class, id);
		return kitMaterial;
	}

	public List<KitMaterial> findKits(KitMaterial kitMaterial) throws BOException, DAOException {
		List<KitMaterial> materiales = kitMaterialDAO.findKitMateriales(kitMaterial);
		return materiales;
	}
	
	public Grid<KitMaterial> findToGrid(KitMaterial kitMaterial, String order, int page, int rows)
	throws BOException, DAOException {
		String where="where ";	
		List<KitMaterial> materiales = findKits(kitMaterial);
	    return super.findToGridList(materiales, where, " order by "+order,page,rows);
	}
	
	public void save(KitMaterial kitMaterial) throws BOException, DAOException {
		super.save(kitMaterial);
	}
}